<template>
    <el-dialog :title="state.titleMap[state.mode]" v-model="state.visible" :width="500" destroy-on-close
               @closed="$emit('closed')">
        <el-form :model="state.form" :rules="state.rules" :disabled="state.mode==='show'" ref="dialogForm" label-width="100px">
            <el-form-item label="上级部门" prop="pid">
                <el-cascader v-model="state.form.pid" :options="state.groups" :props="state.groupsProps"
                             :show-all-levels="false" clearable style="width: 100%;"/>
            </el-form-item>
            <el-form-item label="部门名称" prop="label">
                <el-input v-model="state.form.name" placeholder="请输入部门名称" clearable/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="state.form.remark" clearable type="textarea"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="state.visible=false">取 消</el-button>
            <el-button v-if="state.mode !== 'show'" type="primary" :loading="state.isSaveing" @click="submit()">
                保 存
            </el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import departmentApi from '@/api/company/department'
import {getCurrentInstance, onMounted, reactive, ref} from "vue";

const {proxy} = getCurrentInstance()
const emits = defineEmits(['success', 'closed'])
const dialogForm = ref(null)

const state = reactive({
    mode: "add",
    titleMap: {
        add: '新增',
        edit: '编辑',
        show: '查看'
    },
    isSaving: false,
    emits: ['success', 'closed'],
    form: {
        id: "",
        pid: "",
        name: "",
        remark: ""
    },
    rules: {
        name: [
            {required: true, message: '请输入部门名称'}
        ]
    },
    groups: [],
    groupsProps: {
        value: "id",
        label: 'name',
        emitPath: false,
        checkStrictly: true
    }
})

const getGroup = async () => {
    const res = await departmentApi.list.get()
    res.data.unshift({
        id: 0,
        pid: 0,
        name: '顶级部门'
    })
    state.groups = res.data;
}

//表单提交方法
const submit = () => {
    dialogForm.value.validate(async (valid) => {
        if (valid) {
            state.isSaveing = true;
            const res = await departmentApi[state.mode].post(state.form);
            state.isSaveing = false;
            if (res.code === 0) {
                emits('success', state.form, state.mode)
                state.visible = false;
                proxy.$message.success("操作成功")
            } else {
                await proxy.$alert(res.message, "提示", {type: 'error'})
            }
        }
    })
}

onMounted(() => {
    getGroup()
})

const open = (mode = 'add') => {
    state.mode = mode
    state.visible = true
}

const setData = (data) => {
    Object.assign(state.form, data)
}

//暴露给父组件的方法
defineExpose({
    open, setData
})

</script>
